import request from "../../utils/request";
let isSend = false // 函数节流使用
let timer = null //防抖使用
Page({
  /**
   * 页面的初始数据
   */
  data: {
    placeholderContent: "", //placeholder默认内容
    hotList: [], //热搜榜数据
    searchContent: '', //用户输入的搜索关键词
    searchList: [],  //查找到的数据
    historyList: [], //搜索历史记录
    pre: 0, //节流
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取初始化数据
    this.getInitData();
    //获取历史记录
    this.getSearchHistrory()
  },
  //获取本地存储的历史记录功能函数
  getSearchHistrory() {
    let historyList = wx.getStorageSync('searchHistory');
    if(historyList) {
      this.setData({
        historyList
      })
    }
  },
  
  //请求初始化数据
  async getInitData() { 
    let placeholderData = await request("/search/default");
    let hotListData = await request("/search/hot/detail");
    this.setData({
      placeholderContent: placeholderData.data.showKeyword,
      hotList: hotListData.data,
    });
  },
  //
  // 表单项内容发生改变的回调
  handleInputChange(event){
    let searchContent = event.detail.value.trim()
    this.setData({
      searchContent
    })
    //自定义防抖
   if(!timer) {
    timer = setTimeout(() => {
      this.getSearchListData()
    },1000)
   }else{
     clearTimeout(timer)
     timer = setTimeout(() => {
      this.getSearchListData()
    },1000)
   } 
  },
  //请求搜索的数据
  async getSearchListData() {
    let {searchContent, historyList} = this.data
    if(searchContent.length == 0) {
      this.setData({
        searchList: [ ]  
      })
      return;
    }
    let searchList = await request('/search', {keywords: searchContent, limit: 10})
      this.setData({
        searchList: searchList.result.songs
      })
      
    //添加之前判断是否已经有该关键字
   if(historyList.indexOf(searchContent) != -1)  {
      historyList.splice(historyList.indexOf(searchContent), 1)
   }
   //将搜索的关键字添加到搜索历史记录中
   historyList.unshift(searchContent);
    this.setData({
      historyList
    })
    // 避免刷新初始化,使用本地存储
    wx.setStorageSync('searchHistory', historyList);
    
  },
  //清空搜索内容
  clearSearch() {
    console.log(1);
    this.setData({
      searchContent: '',
      historyList: []
    })
  },
  delete() {
    //清空data中historyList与本地储存Histioy
    wx.showModal({
      content: '确认清空历史记录？',
      success: (result) => {
        if(result.confirm){
          this.setData({
            historyList: []
          })
          wx.removeStorageSync('searchHistory');
        }
      }
    });
   
  },
  // 自定义节流函数
  throttle (fn, delay = 2000) {
    let pre = this.data.pre // 初始值是 0 
    let that = this
    return function () {
        let now = + new Date();
        if(now - pre >= delay) {
            fn.apply(this, arguments)
            that.setData({
                pre: now
            })
        }
    }
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
